package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.LotScrapListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapBean;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapListBean;
import com.glory.hikvisionmobile.bean.LotScrap.XPdaStepMaterial;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.customView.HikLabelEditText;
import com.glory.hikvisionmobile.customView.HikLabelSpinner2;
import com.glory.hikvisionmobile.customView.HikLabelTextView;
import com.glory.hikvisionmobile.customView.HikTabView;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class Lot_LotScrapActivity extends BaseActivity {

    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.lbLotId)
    HikLabelEditText lbLotId;
    @BindView(R.id.lbStepDesc)
    HikLabelTextView lbStepDesc;
    @BindView(R.id.lbRecipe)
    HikLabelTextView lbRecipe;
    @BindView(R.id.lbRecipeDesc)
    HikLabelTextView lbRecipeDesc;
    @BindView(R.id.lbPart)
    HikLabelTextView lbPart;
    @BindView(R.id.lbPartDesc)
    HikLabelTextView lbPartDesc;
    @BindView(R.id.lbLotCount)
    HikLabelTextView lbLotCount;
    @BindView(R.id.lbSpinner_material)
    HikLabelSpinner2 lbSpinner_material;
    @BindView(R.id.lbSpinner_ScrapCode)
    HikLabelSpinner2 lbSpinner_ScrapCode;
    @BindView(R.id.lbScrapCount)
    HikLabelEditText lbScrapCount;
    @BindView(R.id.lbRemarks)
    HikLabelEditText lbRemarks;
    @BindView(R.id.etScrapNum)
    FreeUI_ClearEditText etScrapNum;
    @BindView(R.id.tabView)
    HikTabView tabView;
    @BindView(R.id.listHeader)
    LinearLayout listHeader;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.tvReplay)
    TextView tvReplay;

    private HikLabelSpinner2.HikSimpleSpinnerAdapter scrapCodeAdapter;
    private HikLabelSpinner2.HikSimpleSpinnerAdapter scrapMaterialAdapter;

    private LotScrapListAdapter scrapListAdapter;

    private String lotNum;

    private String scrapCode = "";           //报废码
    private String subUnitType = "";         //报废类型
    private String scrapMatType = "";        //报废形态

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lot_scrap;
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次报废");
        freeUI_titleView.setRightListener("刷新", v -> {
            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    if (editIsEmpty(lbLotId.getLabelContext(), "批次号不能为空")) {
                        reSet();
                        requestData(lbLotId.getLabelContext().getText().toString().trim());
                    }
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        lotNum = bundle.getString("lot");

        initListTitle();

        scrapListAdapter = new LotScrapListAdapter(null);
        scrapListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        scrapListAdapter.isFirstOnly(true);
        scrapListAdapter.setContext(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(Lot_LotScrapActivity.this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(Lot_LotScrapActivity.this, 1));
        recyclerView.setAdapter(scrapListAdapter);

        //报废码
        scrapCodeAdapter = new HikLabelSpinner2.HikSimpleSpinnerAdapter(null);

        lbSpinner_ScrapCode.setAdapter(scrapCodeAdapter);
        lbSpinner_ScrapCode.setOnItemSelectedListener((view, position) -> {
            scrapCode = scrapCodeAdapter.getItem(position).toString().split("/")[0];
            scrapListAdapter.setScrapCode(scrapCode);
        });
        //报废物料形态
        scrapMaterialAdapter = new HikLabelSpinner2.HikSimpleSpinnerAdapter(null);

        lbSpinner_material.setAdapter(scrapMaterialAdapter);
        lbSpinner_material.setOnItemSelectedListener((view, position) -> {
            scrapMatType = ((XPdaStepMaterial) (scrapMaterialAdapter.getItem(position))).getMaterialNames();
        });

        if (!FreeApi_StringUtils.isEmpty(lotNum)){
            lbLotId.getLabelContext().setText(lotNum);
            requestData(lotNum);
        }
        //批次号
        EditTextEnterUtils.initPdaEditText(lbLotId.getLabelContext(),true, text -> {
            requestData(text);
        });
        //报废组件
        EditTextEnterUtils.initPdaEditText(etScrapNum, false, text -> {
            searchLot(text);
        }, text -> {
            int count = -1;
            try {
                count = Integer.valueOf(text);
            } catch (NumberFormatException e) {

            }
            if (count != -1) {
                if (FreeApi_StringUtils.isEmpty(scrapCode)) {
                    showToast("请选择报废码", false);
                    return;
                }
                scrapListAdapter.select(count, scrapCode);
            }
        });
    }

    private void initListTitle() {
        HikTabView.Tab tab1 = new HikTabView.Tab("组件号", 1, Gravity.CENTER);
        HikTabView.Tab tab2 = new HikTabView.Tab("位置", 1, Gravity.CENTER);
        HikTabView.Tab tab3 = new HikTabView.Tab("报废码", 1, Gravity.CENTER);
        HikTabView.Tab tab4 = new HikTabView.Tab("复选框", 1, Gravity.CENTER);
        tabView.setTabs(tab1, tab2, tab3, tab4);
    }

    private void searchLot(String commentID) {
        String contain = "N";
        if (scrapListAdapter.getData() == null || scrapListAdapter.getData().size() <= 0) {
            showToast("未请求到数据", false);
            return;
        }
        if (FreeApi_StringUtils.isEmpty(scrapCode)) {
            showToast("请选择报废码", false);
            return;
        }
        for (int i = 0; i < scrapListAdapter.getData().size(); i++) {
            if (scrapListAdapter.getData().get(i).getComponentId().equals(commentID)) {
                contain = "Y";
                ScrapListBean item = scrapListAdapter.getItem(i);
                item.setCheck(true);
                item.setActionCode(scrapCode);
                etScrapNum.setText("");
                etScrapNum.requestFocus();
                scrapListAdapter.notifyItemChanged(i);
                break;
            }
        }
        if (contain.equals("N")) {
            showToast("未查询到当前组件号", false);
        }
    }

    @Override
    protected void initData() {
        NetUtils.getSelectorList("ScrapCode", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                scrapCodeAdapter.setData(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
    }

    private void requestData(String lotID) {
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lotID);
        map.addProperty("actionType", "");
        NetUtils.requestDara("HIK.PdaLotScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    ScrapBean scrapBean = response.body().getBody();
                    lbLotCount.getLabelContext().setText(scrapBean.getMainQty());
                    lbStepDesc.getLabelContext().setText(scrapBean.getStepDesc());
                    lbRecipe.getLabelContext().setText(scrapBean.getRecipeName());
                    lbPartDesc.getLabelContext().setText(scrapBean.getPartDesc());
                    lbRecipeDesc.getLabelContext().setText(scrapBean.getRecipeDesc());
                    lbPart.getLabelContext().setText(scrapBean.getPartName());

                    if (scrapBean.getxPdaStepMaterials() == null || scrapBean.getxPdaStepMaterials().size() == 0) {
                        lbSpinner_material.setVisibility(View.GONE);
                    } else {
                        lbSpinner_material.setVisibility(View.VISIBLE);
                        scrapMaterialAdapter.setData(scrapBean.getxPdaStepMaterials());
                    }

                    subUnitType = scrapBean.getSubUnitType();
                    if ("ComponentUnit".equals(subUnitType)) {
                        lbScrapCount.setVisibility(View.GONE);
                        scrapListAdapter.setNewData(scrapBean.getxPdaComponents());
                        listHeader.setVisibility(View.VISIBLE);
                    } else {
                        lbScrapCount.setVisibility(View.VISIBLE);
                        listHeader.setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotScrap");
            }
        });
    }

    @OnClick({R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvReplay:
                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (lbRemarks.getLabelContext().getText().toString().trim().length() == 0) {
                            showToast("请输入备注", false);
                            return;
                        }

                        if (scrapMaterialAdapter.getCount() > 0 && FreeApi_StringUtils.isEmpty(scrapMatType)){
                            showToast("请选择报废物料形态", false);
                            return;
                        }

                        if (FreeApi_StringUtils.isEmpty(scrapCode)){
                            showToast("请选择报废码", false);
                            return;
                        }

                        if (subUnitType.equals("ComponentUnit")){
                            if (scrapListAdapter.getSelectorData().size() <= 0) {
                                showToast("当前未选中报废组件", false);
                                return;
                            }
                            DialogUtils.showLoginDialog(Lot_LotScrapActivity.this, Constant.CURRENT_USER, () -> submit(), getSupportFragmentManager());
                        }else {
                            if (editIsEmpty(lbScrapCount.getLabelContext(),"请输入报废数量")){
                                int scrapNum = Integer.parseInt(lbScrapCount.getLabelContext().getText().toString().trim());
                                if (scrapNum <= 0){
                                    showToast("报废数量不能小于0", false);
                                    lbScrapCount.getLabelContext().setText("");
                                    lbScrapCount.getLabelContext().requestFocus();
                                    return;
                                }
                                int qtyNum = Integer.parseInt(lbLotCount.getLabelContext().getText().toString().trim());
                                if (scrapNum > qtyNum){
                                    showToast("报废数量不能大于批数量", false);
                                    lbScrapCount.getLabelContext().setText("");
                                    lbScrapCount.getLabelContext().requestFocus();
                                }else {
                                    DialogUtils.showLoginDialog(Lot_LotScrapActivity.this, Constant.CURRENT_USER, () -> submit(), getSupportFragmentManager());
                                }
                            }
                        }
                    }
                });
                break;
        }
    }

    private void submit() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("lotId", lbLotId.getLabelContext().getText().toString().trim());
        map.put("actionType", "Scrap");
        map.put("scrapComment", lbRemarks.getLabelContext().getText().toString().trim());
        Map<String, Object> xPdaComponents = new LinkedHashMap<>();
        xPdaComponents.put("XPdaComponent", scrapListAdapter.getSelectorData());
        map.put("xPdaComponents", xPdaComponents);
        map.put("actionCode",scrapCode);
        map.put("scrapQty",lbScrapCount.getLabelContext().getText().toString().trim());
        map.put("scrapMatType", scrapMatType);

        NetUtils.requestMapDara("HIK.PdaLotScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showConfirmDialog("报废成功");
                    reSet();
                    requestData(lbLotId.getLabelContext().getText().toString().trim());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotScrap");
            }
        });
    }

    /**
     * 重置
     */
    private void reSet() {
        lbSpinner_ScrapCode.getLabelContext().setText("");
        lbSpinner_material.getLabelContext().setText("");
        scrapCode = "";
        subUnitType = "";
        scrapMatType = "";
        lbRemarks.getLabelContext().setText("");
        etScrapNum.setText("");
        scrapListAdapter.getData().clear();
        scrapListAdapter.notifyDataSetChanged();
        scrapListAdapter.getSelectorData().clear();
        scrapListAdapter.setScrapCode("");
        scrapMaterialAdapter.setData(null);
    }
}
